import React, { useEffect, useState } from "react";
import { useWindowDimensions, StatusBar } from "react-native";
import { SceneMap, TabView } from "react-native-tab-view";
import Contact from "./contact";
import Index from "./index";
import Settings from "./settings";
import Ionicons from "@expo/vector-icons/Ionicons";
import AntDesign from "@expo/vector-icons/AntDesign";
import MaterialCommunityIcons from "@expo/vector-icons/MaterialCommunityIcons";
import TabHeader from "@/components/TabsLayout/Header";
import { SafeAreaView } from "react-native-safe-area-context";
import NotificationFunctions from "@/notification";
import useChatDetailPageState from "@/store/chat-detail-page";
import { router } from "expo-router";
import * as Notifications from "expo-notifications";
import TabBar from "@/components/Tabbar";
import { useTheme } from "@/contexts/ThemeContext";
import { useAuth } from "@/contexts/AuthContext";
import AlertComponent from "@/components/Global/Alert";
import { getSessionBySessionId } from "@/services/sqlite/chat-session";
import { useStompClient } from "@/hooks/stomp/stomp-service";
import {useChatSessionState} from "@/hooks/chat/chat-session";
import { useUserProfileActions } from "@/hooks/user/user-profile";
const { registerForPushNotificationsAsync, unregisterForPushNotifications } =
  NotificationFunctions;

export default function TabsLayout() {
  const { isAuthenticated } = useAuth();
  const layout = useWindowDimensions();
  const [index, setIndex] = useState(0);
  const { themeMode, colors } = useTheme();

  useEffect(() => {
    if (themeMode === "dark") {
      StatusBar.setBarStyle("light-content", true);
      StatusBar.setBackgroundColor(colors.background);
    } else {
      StatusBar.setBarStyle("dark-content", true);
      StatusBar.setBackgroundColor(colors.background);
    }
  }, [themeMode, colors]);

  //region 聊天页面状态储存
  const { setCurrentChatDetailState } = useChatDetailPageState().actions;
  //endregion

  //region 通知相关
  const redirectToSession = (notification: Notifications.Notification) => {
    const sessionId = notification.request.content.data?.sessionId;
    if (sessionId) {
      getSessionBySessionId(sessionId)
        .then((session) => {
          //设置聊天详情页状态
          setCurrentChatDetailState(session);
          //跳转到聊天详细页
          router.navigate("chat/chat_detail");
        })
        .catch((e) => {
          console.error(e);
        });
    }
  };
  //endregion
  const { totalUnreadCount } = useChatSessionState();
  // 用户信息状态
  const { getCurrentUserProfile } = useUserProfileActions();
  const tabsConfig = [
    {
      icon: "people-outline",
      activeIcon: "people",
      label: "通讯录",
    },
    {
      icon: "chatbox-outline",
      activeIcon: "chatbox",
      label: "信息",
      badge: totalUnreadCount && totalUnreadCount > 0 ? totalUnreadCount : 0,
    },
    {
      icon: "settings-outline",
      activeIcon: "settings",
      label: "设置",
    },
  ];

  const { connect , disconnect } = useStompClient();

  useEffect(() => {
    // 组件是否挂载
    let isMounted = true;
    // 添加实际的认证检查，防止未登录状态下的不必要初始化
    if (!isAuthenticated) {
      console.log("TabsLayout: 用户未登录，跳过初始化");
      return;
    }
    console.log("TabsLayout: 用户已登录，执行初始化");
    // 注册通知事件
    registerForPushNotificationsAsync();
    // 注册通知深层链接路由监听器
    Notifications.getLastNotificationResponseAsync().then((response) => {
      if (!isMounted || !response?.notification) {
        return;
      }
      redirectToSession(response?.notification);
    });

    const subscription = Notifications.addNotificationResponseReceivedListener(
      (response) => {
        redirectToSession(response.notification);
      }

    );
    //初始化stomp连接
    connect();
    // 获取当前用户信息
    getCurrentUserProfile();

    return () => {
      // 清除通知事件
      subscription.remove();
      // 清除组件挂载状态
      isMounted = false;
      // 断开连接
      disconnect();
    };
  }, [isAuthenticated]);

  const [routes] = useState([
    {
      key: "contact",
      title: "通讯录",
      icon: <AntDesign name="contacts" size={24} />,
    },
    {
      key: "index",
      title: "信息",
      icon: <MaterialCommunityIcons name="chat-outline" size={24} />,
    },
    {
      key: "settings",
      title: "设置",
      icon: <Ionicons name="settings-outline" size={24} />,
    },
  ]);

  const renderScene = SceneMap({
    contact: Contact,
    index: Index,
    settings: Settings,
  });

  const renderTabBar = () => (
    <TabBar
      tabs={tabsConfig}
      activeIndex={index}
      onTabPress={(i) => {
        setIndex(i);
      }}
    />
  );

  return (
    <SafeAreaView
      style={{
        flex: 1,
        backgroundColor: colors.background,
      }}
      edges={["top", "left", "right"]}
    >
      <TabHeader routes={routes} index={index} />
      <AlertComponent />
      <TabView
        navigationState={{ index, routes }}
        tabBarPosition="bottom"
        renderScene={renderScene}
        onIndexChange={setIndex}
        initialLayout={{ width: layout.width }}
        renderTabBar={renderTabBar}
      />
    </SafeAreaView>
  );
}
